import 'package:geocoding/geocoding.dart';
import 'package:mi_mang_flutter/utils/geolocator_util.dart';
import 'package:mi_mang_flutter/utils/locale_util.dart';

import 'api_strategy.dart';
import 'weather_bean.dart';

/// https://dev.qweather.com/docs/api/weather/weather-now/
/// 这里存放所有的网络请求接口
class ApiService {
  factory ApiService() => _getInstance()!;

  static ApiService? get instance => _getInstance();
  static ApiService? _instance;

  static final int requestSucceed = 0;
  static final int requestFailed = 1;

  ApiService._internal() {
    ///初始化
  }

  static ApiService? _getInstance() {
    if (_instance == null) {
      _instance = new ApiService._internal();
    }
    return _instance;
  }

  // ///获取图片
  // void getPhotos({
  //   Function success,
  //   Function failed,
  //   Function error,
  //   Map<String, String> params,
  //   CancelToken token,
  //   int startPage,
  // }) {
  //   ApiStrategy.getInstance().get(
  //     "https://api.unsplash.com/photos/",
  //     (data) {
  //       if (data.toString().contains("errors")) {
  //         failed(data);
  //       } else {
  //         List<PhotoBean> beans = PhotoBean.fromMapList(data);
  //         success(beans,data);
  //       }
  //     },
  //     params: params,
  //     errorCallBack: (errorMessage) {
  //       error(errorMessage);
  //     },
  //     token: token,
  //   );
  // }

  /// 天气获取
  getWeatherNow({
    Function(WeatherBean, String?)? success,
    Function? errorCallBack,
  }) {
    determinePosition().then((value) async {
      List<Placemark> placemarks = await placemarkFromCoordinates(
        value.latitude,
        value.longitude,
      );
      // for (var item in placemarks) {
      //   print(item.toString());
      // }
      // print(value.latitude.toStringAsFixed(2));
      // print(value.longitude.toStringAsFixed(2));
      ApiStrategy.getInstance()!.get(
        "https://devapi.qweather.com/v7/weather/now",
        (data) {
          WeatherBean weatherBean = WeatherBean.fromJson(data);
          if (weatherBean.code == '200') {
            success!(weatherBean, placemarks.first.locality);
          }
        },
        params: {
          "key": "90cf079327eb4be4855e1183fca59e8c",
          "location": "${value.longitude},${value.latitude}",
          "lang": languageCode(),
        },
        errorCallBack: errorCallBack,
      );
    }).catchError((error) {
      errorCallBack?.call();
    });
  }
}
